<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Iterator接口与Generator函数</title>
</head>
<body>
    <h1>Iterator接口与Generator函数</h1>
    <h2>使用Generator函数实现Iterator接口</h2>

    <script>
        // 使用Generator函数实现Iterator接口
        const myIterable = {
            *[Symbol.iterator]() {
                yield 1;
                yield 2;
                yield 3;
            }
        };

        console.log([...myIterable]); // [1, 2, 3]

        // 为对象添加Iterator接口
        function* objectEntries(obj) {
            const propKeys = Reflect.ownKeys(obj);
            for (const propKey of propKeys) {
                yield [propKey, obj[propKey]];
            }
        }

        const obj = { name: '张三', age: 25 };
        for (const [key, value] of objectEntries(obj)) {
            console.log(`${key}: ${value}`);
        }

        // Generator函数实现对象遍历
        class Collection {
            constructor() {
                this.items = [];
            }

            add(item) {
                this.items.push(item);
            }

            *[Symbol.iterator]() {
                for (let item of this.items) {
                    yield item;
                }
            }
        }

        const collection = new Collection();
        collection.add('A');
        collection.add('B');
        collection.add('C');

        for (let x of collection) {
            console.log(x);
        }
    </script>
</body>
</html> 